package com.qiyu.admin.system.shiro;

import com.qiyu.admin.system.model.User;
import org.apache.shiro.crypto.RandomNumberGenerator;
import org.apache.shiro.crypto.SecureRandomNumberGenerator;
import org.apache.shiro.crypto.hash.SimpleHash;
import org.apache.shiro.util.ByteSource;

/**
 * 密码策略
 *
 * @author zhangqing
 * @date 2016年08月31日
 */
public class EncryptPwd {
    /**
     * 随机数
     */
    private RandomNumberGenerator randomNumberGenerator = new SecureRandomNumberGenerator();
    /**
     * 加密方式
     */
    private String algorithmName = "md5";
    /**
     * 散列次数(加密次数)
     */
    private int hashIterations = 3;

    /**
     * 为用户设置加密策略和盐值
     * @param user 用户
     */
    public void encryptPassword(User user) {
        user.setSalt(randomNumberGenerator.nextBytes().toHex());//增加盐值
        /**
         * 加密策略
         */
        String newPassword = new SimpleHash(algorithmName, user.getLoginPwd(),
                ByteSource.Util.bytes(user.getCredentialsSalt()),
                hashIterations).toHex();
        user.setLoginPwd(newPassword);
    }

    public void setRandomNumberGenerator(RandomNumberGenerator randomNumberGenerator) {
        this.randomNumberGenerator = randomNumberGenerator;
    }

    public void setAlgorithmName(String algorithmName) {
        this.algorithmName = algorithmName;
    }

    public void setHashIterations(int hashIterations) {
        this.hashIterations = hashIterations;
    }

    public static void main(String[] args) {
        User user = new User();
        user.setLoginName("admin");
        user.setLoginPwd("123456");
        EncryptPwd p = new EncryptPwd();
        p.encryptPassword(user);
        System.out.println("salt====="+user.getSalt()+"|||||password:"+user.getLoginPwd());
    }
}
